/*
 * Copyright (c) 2013, FPX and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package com.pyip.simpleioc;

import java.net.URL;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.pyip.simpleioc.beans.BeanException;
import com.pyip.simpleioc.beans.definition.BeanDefinition;
import com.pyip.simpleioc.beans.definition.BeanNotFoundException;
import com.pyip.simpleioc.beans.definition.factory.BeansFactory;
import com.pyip.simpleioc.beans.definition.factory.BeansFactoryImpl;
import com.pyip.simpleioc.load.xml.XmlParser;

/**
 * @author yepeng
 * @date 2015年11月4日
 */
public class SimpleIocContextImpl implements SimpleIocContext {

    private XmlParser xmlParser;
    private BeansFactory beansFactory;
    private Map<String, BeanDefinition> beanDefinitionMap;

    public SimpleIocContextImpl(String configPath) {
        URL configUrl = ClassLoader.getSystemResource(configPath);
        if (configUrl == null) {
            throw new BeanException(configPath + " not found");
        }
        xmlParser = new XmlParser();
        beansFactory = new BeansFactoryImpl();

        String absolutePath = ClassLoader.getSystemResource(configPath).getPath();
        beanDefinitionMap = xmlParser.parseXML(absolutePath);
        beansFactory.doDefinition(beanDefinitionMap);
    }

    @Override
    public Object getBean(String id) throws BeanException {
        if (StringUtils.isBlank(id)) {
            throw new NullPointerException("参数id不能为空");
        }
        BeanDefinition defination = beanDefinitionMap.get(id);
        if (defination == null) {
            throw new BeanNotFoundException("获取bean失败, id: " + id);
        }

        return defination.getObject();
    }

    @Override
    public <T> T getBean(Class<T> requiredType) throws BeanException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isSingleton(String name) throws BeanException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isPrototype(String name) throws BeanException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void close() {
        // TODO Auto-generated method stub

    }
}
